package br.urca.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import br.urca.dao.AlunoDAO;
import br.urca.model.Aluno;

@Transactional
public class JPAAlunoDAO implements AlunoDAO{
	
	private EntityManager manager;
	
	public JPAAlunoDAO() { 
		this(null);
	}
	
	@Inject
	public JPAAlunoDAO(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public List<Aluno> todos() {
		return this.manager.createQuery("SELECT a FROM Aluno a", Aluno.class)
				.getResultList();
	}

	@Override
	public void salvar(Aluno aluno) {
		if (aluno.getId() == null) {
			gerarIdAluno(aluno);
			this.manager.persist(aluno);
		} else {
			this.manager.merge(aluno);
		}		
	}
	
	public void gerarIdAluno(Aluno aluno) {
		Long id = (Long) this.manager.createQuery("SELECT MAX(a.id) FROM Aluno a").getSingleResult();
		id++;
		aluno.setId(id);
	}

}
